<template>
  <div style="width: 1366px; height: 600px; margin-top: 18px;background-image: url(http://127.0.0.1:8080/ipfs/QmcjuMDQEuxuKeLsjR34o4hHwCaG7K6KADuWeQprjgo1kx);backdrop-filter: blur(5px); position: relative; padding:1px;
    box-sizing:border-box;z-index:1;background-size: 1366px 600px;">
    <!-- <el-header style="text-align: right; font-size: 12px">
      <el-button
        @click="drawer = true"
        type="primary"
        style="margin-left: 16px"
      >
        连接信息
      </el-button>
    </el-header> -->

    <!-- <el-drawer title="我是标题" :visible.sync="drawer" :with-header="false"> -->
      <!--metamask-->
      <!-- <el-card style="margin: 10px">
        <el-tag style="margin-left: 1px; float: right">metamask</el-tag>
        <hellometa />
      </el-card> -->
      <!--ipfs-->
      <!-- <el-card tyle="margin: 10px">
        <el-tag style="margin-left: 1px; float: right">{{ status }}</el-tag>
        <br />
        <br />
        <div v-if="!ipfs">
          <p>填写你的服务器链接</p>
          <el-input style="width: 200px" type="text" v-model="node" />
          <el-button type="primary" @click="connect">连接ipfs</el-button>
        </div>
        <div v-else>
          <el-form label-width="80px">
            <el-form-item label="ID">
              <el-input
                readonly
                v-model="id"
                style="width: 250px; float: left"
              ></el-input>
            </el-form-item>
            <el-form-item label="Agent">
              <el-input
                readonly
                v-model="agentVersion"
                style="width: 250px; float: left"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </el-drawer> -->

    <!-- <div style="margin: 20px">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>数字资产认证</el-breadcrumb-item>
      </el-breadcrumb>
    </div> -->
     <p style="font-size: 45px;font-weight: bold;color: #383838; margin-top: 25px;">上传一幅作品，创建一份独一无二的数字资产</p>
    <el-card
      class="back"
      style="width: 1200px; margin: 20px auto; padding-bottom: 40px; background-color: #fff; margin-top: 50px; border-radius: 15px;
      background-image: url(http://127.0.0.1:8080/ipfs/Qmba3q7KurUiK1pNyygnhCKL7C9Q7cHDu9wxpVhtgVCVvj);"
    >
      <div>
        <div style="float: left; width: 700px; padding: 10px;">
          <h2 style="margin-right: 200px; color: #535962;">上传文件</h2>
          <div
            style="width: 250px; heught: 400px; border: 1px; margin-left: 200px"
          >
            <el-upload
              class="avatar-uploader"
              action="#"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="uploadImage"
              style="border-width: 3px; border-color: #aaaaaa;"
            >
              <img v-if="src" :src="src" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
          <p v-show="hashCode" style="font-size: 1px; color: rgb(169,169,169)">
            文件哈希值为：{{ hashCode }}
          </p>
        </div>
        <div style="float: left; width: 400px; margin-top: 50px">
          <el-form
            label-width="80px"
            :rules="rules"
            ref="inputform"
            :model="inputform"
          >
            <el-form-item label="名称" prop="name">
              <el-input
                v-model="inputform.name"
                placeholder="请输入名称"
                style="width: 300px"
              ></el-input>
            </el-form-item>
            <el-form-item label="作品描述">
              <el-input
                v-model="inputform.describ"
                style="width: 300px"
                placeholder="请输入描述"
                type="textarea"
                :rows="4"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="addNFT('inputform')" type="primary"
                >上链</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!-- <div style="width: 50px; height: 30px"></div> -->
    </el-card>
    <el-dialog
    class="thedialog"
      title="你成功创建了一个新的数字资产！"
      :visible.sync="dialogVisible"
      width="30%"
      style="padding:0px 10px"
    >
      <el-form label-width="80px" style="margin:">
        <img
          style="width: 200px; margin: 20px auto"
          v-if="src"
          :src="src"
          class="avatar"
        />

        <el-form-item label="名称">
          <el-input
            v-model="inputform.name"
            style="width: 300px"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="作品描述">
          <el-input
            v-model="inputform.describ"
            style="width: 300px"
            type="textarea"
            :disabled="true"
            :rows="4"
          ></el-input>
        </el-form-item>
        <el-form-item label="交易号">
          <el-input
            v-model="dealid"
            style="width: 300px"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="哈希值">
          <el-input
            v-model="hashCode"
            style="width: 300px"
            :disabled="true"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="queding">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import metamask from "./meta";
import IpfsHttpClient from "ipfs-http-client";
export default {
  name: "firstpage",
  data() {
    return {
      dialogVisible: false,

      drawer: false,
      inputform: {
        name: "",
        describ: "",
      },
      returnurl: "",
      dealid: "",
      nftid: 0,

      node: "/ip4/127.0.0.1/tcp/5001",
      ipfs: null,
      status: "未连接ipfs",
      id: "",
      agentVersion: "",
      hashCode: "",
      reader: "",
      src: "",
      imgfile: "",
      imageUrl: "",

      rules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { min: 2, max: 10, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
      },
    };
  },
  created() {},
  mounted() {
    console.log("dispatching getContractInstance");
    this.$store.dispatch("getContractInstance");
    
  },
  components: {
    hellometa: metamask,
  },
  methods: {
    queding() {
      this.dialogVisible = false;
      location.reload();
    },

    async addNFT(formName) {
      console.log(this.$refs[formName]);
      let that = this;
      await this.$refs[formName].validate((valid) => {
        if (valid) {
          //alert("submit!");
          if (typeof this.$store.state.contractInstance !== "function") {
            console.log(
              "typeof this.$store.state.contractInstance !== function"
            );
            this.$store.dispatch("getContractInstance");
          }
          //console.log("haha" , this.$store.state.contractInstance());
          return this.$store.state.contractInstance().mint(
            this.inputform.name,
            this.src,
            this.inputform.describ,
            {
              gas: 300000,
              from: this.$store.state.web3.coinbase,
            },
            function (error, result) {
              if (!error) {
                console.log(result);
                that.dealid = result;
                that.dialogVisible = true;
              } else console.error(error);
            }
            // (res) => {
            //   console.log(res)
            //  this.dealid = res;
            //
            // }
          );
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    async getNFT() {
      await this.getNFTID();
      let that = this;
      console.log(that.nftid);
      await this.$store.state.contractInstance().NFTS.call(
        that.nftid - 1,
        //用call返回一个结果，不使用call，返回的则是交易id
        {
          //gas: 300000,
          from: this.$store.state.web3.coinbase,
        },
        function (err, res) {
          that.returnurl = res[4]; //返回id为参数的NFT的url
        }
      );
    },
    async getNFTID() {
      let that = this;
      await this.$store.state.contractInstance().NFTID.call(
        //用call返回一个结果，不使用call，返回的则是交易id
        {
          //gas: 300000,
          from: this.$store.state.web3.coinbase,
        },
        function (err, res) {
          that.nftid = parseInt(res); //返回NFT的个数
        }
      );
    },
    async getUserNft() {
      let that = this;
      await this.$store.state.contractInstance().findByAddress.call(
        {
          gas: 300000,
          from: this.$store.state.web3.coinbase,
        },
        function (err, res) {
          console.log(parseInt(res[1])); //返回NFT的个数
        }
      );
    },
    Return() {
      this.$router.push("/");
    },

    connect() {
      this.ipfs = IpfsHttpClient(this.node);
      console.log("this.node:" + this.node);
      console.log("this.ipfs:" + this.ipfs);
      this.getIpfsNodeInfo();
    },
    async getIpfsNodeInfo() {
      try {
        const { agentVersion, id } = await this.ipfs.id();
        this.agentVersion = agentVersion;
        this.id = id;
        this.status = "已连接到 IPFS";
      } catch (err) {
        // Set error status text.
        this.status = `getIpfsNodeInfo报错: ${err}`;
      }
    },

    async uploadImage() {
      await this.connect()
      console.log("hello");
      let file = event.target.files[0];
      //let file = this.imgfile;
      console.log(file);
      this.reader = new window.FileReader();
      console.log("reader: " + this.reader);
      this.reader.readAsArrayBuffer(file);

      this.reader.onloadend = () => {
        this.buffer = Buffer.from(this.reader.result);
        console.log("reader.result: " + this.reader.result);
        console.log("this.buffer: " + this.buffer);
        this.saveToIpfs();
        // }
      };
    },
    // 上传文件到ipfs的方法
    async saveToIpfs() {
      try {
        let added = await this.ipfs.add(this.buffer);
        console.log(added[0].path);
        // 获取上传文件hash值
        this.hashCode = added[0].path;
        // this.hashCode = `${added.path}`
        this.src = `http://127.0.0.1:8080/ipfs/${added[0].path}`;

        console.log(this.hashCode);
      } catch (err) {
        console.error("saveToIpfs:" + err);
      }
    },
  },
};
</script>

<style scoped>
.el-header {
  background-color: #2d353f;
  color: rgb(255, 255, 255);
  line-height: 60px;
}
.avatar-uploader {
  border: 1px dashed #c4c0c0;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
}
.avatar-uploader :hover {
  color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.back {
  background-color: rgb(233, 233, 233);
}


</style>

<style>
.thedialog .el-dialog__body {
  padding: 20px;
  padding-top: 0px;
  padding-bottom: 10px;
  color: #606266;
  font-size: 14px;
}
</style>